<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\RegistrationInterface;
use App\Repository\Contracts\RegistrationJavaInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 14:59
 *
 * @Description:
 */
class RegistrationRepository extends Repository implements RegistrationInterface
{
    protected $rules = [
        'created' => [
            'uid' => 'required|exists:admin,uid',
            'type' => 'required|integer',
            'memo' => 'required|min:2|max:255'
        ],
        'updated' => [
            'uid' => 'required|exists:admin,uid',
            'type' => 'required|integer',
            'memo' => 'required|min:2|max:255'
        ]
    ];

    protected $messages = [
        'uid.required' => "管理员 ID 不能为空",
        'uid.exists' => "管理员 ID 不存在",
        'type.integer' => "类型必须为整数",
        'memo.required' => "备注不能为空",
        'memo.min' => "备注不能少于 2 个汉字",
        'memo.max' => "备注不能多于 255 个汉字"
    ];

    protected function modelName()
    {
        return 'App\Model\Registration';
    }

    public function lists($limit, $page)
    {
        $query = $this->model;
        $total = $query->count();
        $data = $query->orderBy('id', 'desc')->with('admin')->simplePaginate($limit, ['*'], 'page', $page);
        $list = [];
        foreach ($data as $key => $val) {
            $list[$key] = $val;
            $list[$key]['admin_name'] = $val->admin->real_name;
        }

        return $this->simplePaginate('list', $list, $total, ceil($total/$limit), $page);
    }

    public function detail($id)
    {
        return $this->find($id);
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
        if (env('DIRECT_SALE') && env('JAVA_NETWORK')) {
            $result = $this->container->make(RegistrationJavaInterface::class)->syncCreated($data['store_id'], $data);
            if ($result['resultType' === 'success']) {

                return $this->save($data);
            }

            throw new ValidateException('当前处于离线状态,请稍后');
        }

        return $this->save($data);
    }
}